<template>
    <div class="map-container">
        <!-- 搜索组件 -->
           <!-- 全屏按钮 -->
        <button class="fullscreen-btn" @click="toggleFullscreen">
            <i :class="fullscreenIcon"></i>
        </button>
        <map-search v-if="enableSearch && map" :map-instance="map" :search-options="searchOptions" @select="handlePlaceSelect"/>
        <div ref="mapContainer" id="container" class="amap"></div>
        <div class="map-type-control">
            <button v-for="(style, name) in mapStyles" :key="name" @click="changeMapStyle(style)">{{ name }}</button>
        </div>
        <div id="panel" class="info-panel"></div>
    </div>
</template>

<script lang="ts">
import { Component, Vue ,Prop} from 'vue-property-decorator';
import { initAMapSecurity } from '@/utils/amap-helper';
import AMapLoader from '@amap/amap-jsapi-loader';

import MapSearch from './MapSearch.vue';
// 高德地图类型声明
declare const AMap: any ;

@Component({
  components: { MapSearch }
})
export default class WalkingMap extends Vue {
    @Prop({ type: Boolean, default: false }) enableSearch!: boolean;
    @Prop({ type: Object, default: () => ({}) }) searchOptions;
    @Prop({ type: Array, default: () => [111.670801, 40.818311] }) center!: number[];
    @Prop({ type: Number, default: 14 }) zoom!: number;
    private map: any = null;
    private walking: any = null;
    private placeSearch: any = null;
    
    // 地图配置
    private mapOptions:any = {
        key: process.env.VUE_APP_AMAP_KEY, // 替换为你的实际key
        //version: "1.4.15",
        version: "2.0",
        plugins: [],

    };

    mounted() {
        this.initMap();
    }

   private getRequiredPlugins() {
    const plugins = ['AMap.Marker',"AMap.Walking","AMap.Scale","AMap.ControlBar"];
    if (this.enableSearch) {
      plugins.push('AMap.PlaceSearch', 'AMap.AutoComplete');
    }
    return plugins;
  }

    // 初始化地图
    private async initMap() {
        initAMapSecurity();
        try {
            this.mapOptions.plugins = this.getRequiredPlugins();
            await AMapLoader.load(this.mapOptions);
            this.initAMap();
        } catch (error) {
            console.error('地图加载失败:', error);
        }
        if (this.enableSearch) this.initSearchService();
    }

    // 预定义地图样式集合
    mapStyles = {
        '标准': 'amap://styles/normal',
        '深色': 'amap://styles/dark',
        '卫星': 'amap://styles/satellite',
        '路网': 'amap://styles/roadnet',
        '月光': 'amap://styles/moon',
        '马卡龙': 'amap://styles/fresh',
        '青草': 'amap://styles/grass',
        '极夜蓝': 'amap://styles/blue'
    }

    private initAMap() {
        // 创建地图实例
        this.map = new AMap.Map(this.$refs.mapContainer as HTMLElement, {
            center: this.center,
            zoom: this.zoom,
            mapStyle: this.mapStyles['标准'],
            optimizeMode: true,  // 开启优化模式
            viewMode: '3D',      // 启用3D渲染
            terrain: true,       // 开启3D地形渲染

            showIndoorMap: false,// 关闭室内地图
            WebGLParams: {       // WebGL参数
                preserveDrawingBuffer: true,
                rotateEnable: true,   // 禁用旋转
                pitchEnable: true
            }
        });

        AMap.plugin(['AMap.ControlBar', 'AMap.ToolBar'], () => { //异步加载插件
          var controlBar = new AMap.ControlBar({ //控制地图旋转插件
              position: {
                  right: '10px',
                  top: '10px'
              }
          });
          this.map.addControl(controlBar);
          var toolBar = new AMap.ToolBar({ //地图缩放插件
              position: {
                  right: '40px',
                  top: '110px'
              }
          });
          this.map.addControl(toolBar)
        });
        // 初始化步行路线规划
        this.initWalkingRoute();
       this.map.on('hotspotover', () => {
        console.log('触发地图鼠标滑过热点时的事件');
        });
    }

    private initSearchService() {
        // 添加容错配置
    this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
        pageSize: 5,
        extensions: 'all',
        showCover: false,
        city: this.searchOptions.city || '内蒙古自治区',
        lang: 'zh_cn',
        children: 0,
        ...this.searchOptions
    });
    
    // 添加错误监听
    this.placeSearch.on('error', (error: any) => {
        console.error('搜索服务错误:', error);
    });
  }

  private handlePlaceSelect(item: any) {
    this.addMarkers([item])
  }

  private addMarkers(pois: any[]) {
    pois.forEach(poi => {
      const marker = new AMap.Marker({
        position: poi.location,
        title: poi.name,
        map: this.map  
      });
      marker.on('click', () => this.showInfoWindow(poi));
    });
    this.map.setFitView();
  }

  private clearMarkers() {
    this.map.clearMap();
  }

  private showInfoWindow(poi: any) {
        const infoWindow = new AMap.InfoWindow({
            content: this.getInfoContent(poi), 
            offset: new AMap.Pixel(0, -30)
        });
        infoWindow.open(this.map,  poi.location); 
    }

  private getInfoContent(poi: any) {
   
    return `<div class="custom-info-window">
      <h3>${poi.name}</h3>
      <p>地址：${poi.address || '无'}</p>
      <p>电话：${poi.tel || '无'}</p>
    </div>`;
  }

    changeMapStyle(styleUrl) {
        if (!this.map) {
            return
        }

        this.map.getAllOverlays('tilelayer').forEach(layer => this.map.remove(layer))
        this.map.setMapStyle(styleUrl)

        // 特殊处理卫星地图叠加路网
        if (styleUrl.includes('satellite')) {
            this.map.setFeatures(['bg', 'road', 'point']) // 显示路网标签
        }

    }

    // 初始化步行导航
    private initWalkingRoute() {
        this.walking = new AMap.Walking({
            map: this.map,
            panel: "panel",
            hideMarkers: false,
            isOutline: true,
            outlineColor: '#ffeeee',
            autoFitView: true
        });

        // 设置起终点坐标
        const start: [number, number] = [111.670801, 40.818311];
        const end: [number, number] = [111.674801, 40.818711];

        // 执行路线规划
        this.walking.search(start, end, (status: string, result: any) => {
            if (status === 'complete') {
                console.log('步行路线规划成功:', result);
            } else {
                console.error('步行路线规划失败:', result);
            }
        });
    }

    beforeDestroy() {
        // 销毁地图实例
        if (this.map) {
            this.map.destroy();
        }
        // 移除监听器
        document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
        document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange);
        document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange);
        document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange);
  
    }

    // 新增全屏状态
  private isFullscreen = false;

  // 计算属性
  private get fullscreenIcon() {
    return this.isFullscreen ? 'el-icon-close' : 'el-icon-full-screen';
  }

  // 全屏切换方法
  private toggleFullscreen() {
    if (!this.isFullscreen) {
      this.enterFullscreen();
    } else {
      this.exitFullscreen();
    }
  }

  // 进入全屏
  private enterFullscreen() {
    const container = this.$el.querySelector('.amap') as HTMLElement;
    
    if (container) {
      const requestMethod = container.requestFullscreen 
                     

      if (requestMethod) {
        requestMethod.call(container);
        this.isFullscreen = true;
      }
    }
  }

  // 退出全屏
  private exitFullscreen() {
    const exitMethod = document.exitFullscreen || 
                      (document as any).webkitExitFullscreen || 
                      (document as any).mozCancelFullScreen || 
                      (document as any).msExitFullscreen;

    if (exitMethod) {
      exitMethod.call(document);
      this.isFullscreen = false;
    }
  }

  // 添加全屏监听
  private addFullscreenListener() {
    document.addEventListener('fullscreenchange', this.handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', this.handleFullscreenChange);
    document.addEventListener('MSFullscreenChange', this.handleFullscreenChange);
  }

  // 处理全屏状态变化
  private handleFullscreenChange() {
    this.isFullscreen = !!(
      document.fullscreenElement ||
      (document as any).webkitFullscreenElement ||
      (document as any).mozFullScreenElement ||
      (document as any).msFullscreenElement
    );
  }
}
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 100vh;
    position: relative;
}

#container {
    width: 100%;
    height: 100%;
}

.info-panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
    z-index: 999;
}

/* 覆盖高德默认样式 */
:deep(.amap-call) {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
}

:deep(.amap-lib-walking) {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
}

.amap {
    width: 100%;
    height: 100%;
}


.map-type-control {
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 999;
    background: white;
    padding: 8px;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

.map-type-control button {
    display: block;
    margin: 4px 0;
    padding: 6px 12px;
    cursor: pointer;
}

:deep(.amap-info-content) {
  padding: 10px;
  min-width: 200px;
  min-height: 100px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.3);
}

:deep(.amap-info-close) {
  right: 5px;
  top: 5px;
}

/* 自定义信息窗口样式 */
:deep(.custom-info-window) {
    padding: 10px;
    min-width: 200px;
}
 
:deep(.custom-info-window h4) {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 16px;
}
 
:deep(.custom-info-window p) {
    margin: 5px 0;
    color: #666;
    font-size: 14px;
    display: flex;
    align-items: center;
}
 
:deep(.custom-info-window i) {
    margin-right: 5px;
    color: #409eff;
}

/* 全屏按钮样式 */
.fullscreen-btn {
  position: absolute;
  z-index: 1000;
  left: 20px;
  bottom: 20px;
  width: 32px;
  height: 32px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.fullscreen-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

/* 全屏状态样式 */
:fullscreen .amap,
:-webkit-full-screen .amap,
:-moz-full-screen .amap,
:-ms-fullscreen .amap {
  width: 100vw !important;
  height: 100vh !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
}
</style>